﻿using System;
using System.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using PanGu;
using PanGu.HighLight;

namespace LuceneApiServer
{
    /// <summary>
    ///     表示字段信息
    ///     字段名自动转换为小写
    /// </summary>
    [Serializable]
    [DebuggerDisplay("Name ={Name}, Value = {Value}, Index = {Index},Store = {Store}")]
    public class LnField
    {
        /// <summary>
        ///     字段名小写
        /// </summary>
        private string _name;

        /// <summary>
        ///     获取或设置字段名
        /// </summary>
        public string Name
        {
            get { return _name; }
            set { _name = value.ToLower(); }
        }

        /// <summary>
        ///     获取或设置值
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        ///     设置分词
        /// </summary>
        public Field.Index Index { get; set; }

        /// <summary>
        ///     设置存储
        /// </summary>
        public Field.Store Store { get; set; }

        /// <summary>
        ///     设置高亮
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="matchField">字段信息</param>
        /// <returns></returns>
        public void SetHighLight(string keywords, LnMatchField matchField)
        {
            var format = new SimpleHTMLFormatter(matchField.KeywordPrefix, matchField.KeywordSuffix);
            var highLighter = new Highlighter(format, new Segment());
            highLighter.FragmentSize = matchField.FragmentSize < 1 ? Value.Length : matchField.FragmentSize;
            var newValue = highLighter.GetBestFragment(keywords, Value);

            if (string.IsNullOrEmpty(newValue) == false)
            {
                Value = newValue;
            }
        }

        /// <summary>
        ///     转换为Field类型
        /// </summary>
        /// <returns></returns>
        public Field ToField()
        {
            return new Field(Name, Value, Store, Index);
        }

        /// <summary>
        ///     转换为Term类型
        /// </summary>
        /// <returns></returns>
        public Term ToTerm()
        {
            if (Name == "id")
            {
                return new Term(Name, Value);
            }
            return null;
        }
    }
}